package com.audaque.springboot.foshanupload.core.component;

import com.audaque.springboot.foshanupload.core.inface.ModelConvertor;
import org.modelmapper.ModelMapper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zgb
 * 只复制非null属性，只匹配属性名称，与属性类型无关
 * 浅拷贝：如果属性是引用类型，拷贝的就是内存地址（即复制引用但不复制引用的对象） ，因此如果其中一个属性引用的对象改变了这个地址，就会影响到引用它的属性。
 * @date 2023-03-08 18:24:54
 */
@Component
public class ModelMapperConvertor implements ModelConvertor {
    @Resource
    private ModelMapper modelMapper;



    public final <S, D> D convert(S source, Class<D> destinationType) {
        if (source == null) {
            return null;
        } else {
            return  this.modelMapper.map(source, destinationType);
        }
    }

    public <S, D> List<D> convert(Collection<S> source, Class<D> destinationType) {
        return (List)source.stream().map((s) -> {
            return this.convert(s, destinationType);
        }).collect(Collectors.toList());
    }

    public void convert(Object s, Object d) {
        if (s != null) {
            this.modelMapper.map(s, d);
        }
    }
}
